package org.daochong.spring;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.daochong.lang.DefaultEventHandler;
import org.daochong.lang.EventListener;
import org.daochong.lang.ThreadPool;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringEventHandler extends DefaultEventHandler implements InitializingBean, ApplicationContextAware {

	private ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@SuppressWarnings(value = { "rawtypes", "unchecked" })
	public void afterPropertiesSet() throws Exception {
		if (this.listeners == null) {
			this.listeners = new HashMap<Class<? extends Object>, List<EventListener<Object>>>();
			try {
				Map<String, EventListener> ls = this.applicationContext.getBeansOfType(EventListener.class);
				if (ls != null) {
					for (EventListener listener : ls.values()) {
						Class<?> clazz = listener.getListenerClass();
						List<EventListener<Object>> list = this.listeners.get(clazz);
						if (list == null) {
							list = new ArrayList<EventListener<Object>>();
							this.listeners.put(clazz, list);
						}
						list.add(listener);
					}
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		if (this.threadPool == null) {
			try {
				this.threadPool = this.applicationContext.getBean(ThreadPool.class);
				if (this.threadPool == null) {
					this.threadPool = new ThreadPool();
				}
			} catch (Throwable e) {
				this.threadPool = new ThreadPool();
			}
		}
	}

}
